﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace LibExtend
{
    public partial class MainView : Control
    {
        public event TableView.ItemClickHandler ItemLicked;
        public event LibExtend.Events.DataExchangeHandler DataExchange;
        public event EventHandler OnRefresh;
        public event EventHandler ShowBusyTable;
        
        public DataTable Tables
        {
            get;
            set;
        }

        private DataTable _Pos = new DataTable();
        public DataTable Position
        {
            get { return _Pos; }
            set
            { 
                _Pos = value;
                ResetPos();
            }
        }

        LibExtend.DragForm fDrag = null;
        internal bool isDrag = false;
        private Point p_Mouse = Point.Empty;

        public MainView()
        {
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);

            InitializeComponent();

            fDrag = new LibExtend.DragForm();
            fDrag.FormDragged += new DragForm.FormDraggedHandler(fDrag_FormDragged);
        }

        public void fDrag_FormDragged(TableView View, Table Item, bool Dragged, Point MousePoint)
        {
            isDrag = Dragged;

            DevExpress.XtraTab.XtraTabPage page = GetPageByPoint(MousePoint);
            if (!object.Equals(page, null))
            {
                tab.SelectedTabPage = page;
                View = ((TableView)tab.SelectedTabPage.Tag);
                fDrag.TableView = View;
            }

            Point mP = this.PointToClient(MousePoint);
            if (mP.X >= 0 && mP.Y >= 0 && mP.X <= this.Width && mP.Y <= this.Height)
            {
                fDrag.lblOut.Visible = false;
                p_Mouse = mP;
            }
            else
                fDrag.lblOut.Visible = true;

            View.Invalidate(MousePoint);
            
            if (!isDrag)
            {
                Table celDrop = View.GetTable(MousePoint);
                if (!object.Equals(celDrop, null))
                {
                    if (Item.IdBan == celDrop.IdBan) return;

                    LibExtend.OptionFrom op = new LibExtend.OptionFrom();
                    op.StartPosition = FormStartPosition.Manual;
                    op.FromTable = Item;
                    op.ToTable = celDrop;

                    Point pShow = this.PointToScreen(new Point(this.Width / 2 - op.Width / 2, this.Height / 2 - op.Height / 2));
                    op.Location = pShow;
                    op.DataExchange += new LibExtend.Events.DataExchangeHandler(op_DataExchange);
                    op.Show();
                }
            }
        }

        void op_DataExchange(Events.Sender sender)
        {
            if (this.DataExchange != null)
            {
                this.DataExchange(sender);
                ((TableView)tab.SelectedTabPage.Tag).Invalidate();
            }
        }

        public void StartDrag(TableView View, Table Item, Point Point)
        {
            if (!fDrag.Visible)
            {
                fDrag.StartPosition = FormStartPosition.Manual;
                fDrag.Table = Item;
                fDrag.TableView = View;
                fDrag._SendMessage(Point.X, Point.Y);
                fDrag.Show();
            }
        }

        private bool IsVaild(int v_Pos)
        {
            if (Tables == null || Tables.Rows.Count <= 0) return false;
            DataRow[] rS = Tables.Select("IdViTri=" + v_Pos);
            if (object.Equals(rS, null) || rS.Length <= 0)
                return false;

            return true;
        }

        private void ResetPos()
        {
            if (_Pos != null && _Pos.Rows.Count > 0)
            {
                tab.TabPages.Clear();
                foreach (DataRow row in _Pos.Rows)
                {
                    if (!IsVaild(Convert.ToInt32(row["IdViTri"]))) continue;

                    DevExpress.XtraTab.XtraTabPage tp = new DevExpress.XtraTab.XtraTabPage();
                    tp.Text = row["TenViTri"].ToString();
                    tab.TabPages.Add(tp);

                    TableView tbl = new TableView();
                    tbl.Owner = this;
                    tbl.SperatorWidth = 40;
                    tbl.Tag = Convert.ToInt32(row["IdViTri"]);
                    tbl.Visible = false;
                    tbl.ItemData = Tables.Select("IdViTri=" + Convert.ToInt32(row["IdViTri"]));
                    this.Controls.Add(tbl);
                    tbl.Dock = DockStyle.Fill;
                    tbl.BringToFront();
                    tbl.ItemLicked += new TableView.ItemClickHandler(tbl_ItemLicked);
                    tbl.DataExchange += new LibExtend.Events.DataExchangeHandler(tbl_DataExchange);
                    tp.Tag = tbl;
                }
            }
            if (tab.TabPages.Count > 0)
                Reset();
        }

        void tbl_DataExchange(Events.Sender sender)
        {
            if (this.DataExchange != null)
                this.DataExchange(sender);
        }

        DevExpress.XtraTab.XtraTabPage GetPageByPoint(Point point)
        {
            Point mP = tab.PointToClient(point);

            for (int i = 0; i < tab.TabPages.Count; i++)
            {
                DevExpress.XtraTab.ViewInfo.XtraTabHitInfo _if = tab.CalcHitInfo(mP);
                
                if (!object.Equals(_if.Page, null))
                    return _if.Page;
            }
            return null;
        }

        void tbl_ItemLicked(Table Item)
        {
            if (ItemLicked != null)
                ItemLicked(Item);
        }

        private void Reset()
        {
            foreach (DevExpress.XtraTab.XtraTabPage tp in tab.TabPages)
                if (!object.Equals(tp.Tag, null))
                    ((TableView)tp.Tag).Visible = false;

            if (!object.Equals(tab.SelectedTabPage, null) && !object.Equals(tab.SelectedTabPage.Tag, null))
                ((TableView)tab.SelectedTabPage.Tag).Visible = true;
        }

        private void tab_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            Reset();
        }

        public void lbRef_Click(object sender, EventArgs e)
        {
            int isl = tab.SelectedTabPageIndex;
            if (this.OnRefresh != null)
                this.OnRefresh(((TableView)tab.SelectedTabPage.Tag), e);

            if (isl < tab.TabPages.Count)
                tab.SelectedTabPageIndex = isl;
        }

        private void chk_CheckedChanged(object sender, EventArgs e)
        {
            if (ShowBusyTable != null)
                ShowBusyTable(chk.Checked, e);
        }

        public void AddItem(DataRow row)
        {
            DevExpress.XtraTab.XtraTabPage page = tab.SelectedTabPage;
            if (!object.Equals(page, null))
            {
                tab.SelectedTabPage = page;
                TableView currView = ((TableView)tab.SelectedTabPage.Tag);
                currView.AddItem(row);
            }
        }

        private void txtFind_TextChanged(object sender, EventArgs e)
        {
            DoFind();
        }

        private void DoFind()
        {
            if (this.Tables != null && this.Tables.Rows.Count > 0)
            {
                DataRow[] rS = this.Tables.Select("TenBan='" + txtFind.Text + "'");
                if (!object.Equals(rS, null) || rS.Length > 0)
                {
                    foreach (DevExpress.XtraTab.XtraTabPage page in tab.TabPages)
                    {
                        TableView m_view = (TableView)page.Tag;

                        int m_idvitri = Convert.ToInt32(m_view.Tag);
                        DataRow[] m_rows = Tables.Select("TenBan='" + txtFind.Text + "' And IdViTri =" + m_idvitri);
                        m_view.DataShow = m_rows;
                        if (!object.Equals(m_rows, null) && m_rows.Length > 0)
                            tab.SelectedTabPage = page;
                        m_view.Invalidate();
                    }
                }
            }
        }

        private void txtFind_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TableView m_view = (TableView)tab.SelectedTabPage.Tag;
                m_view.RunShowDetail(txtFind.Text);
            }
        }
    }
}
